package host

import (
	"fmt"
	"g_ansible/ansible/model"
	"g_ansible/global"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(g model.V1Group) error {
	//查询分组是否存在
	cfg := global.Ini
	//分组存在
	if !cfg.HasSection(g.Name) {
		//拼接字符串
		//name1 ansible_host
		//192.168.84.200 ansible_port=22 ansible_ssh_user=root ansible_ssh_pass=Lvshicong990!
		//分组不存在
		_, err := cfg.NewSection(g.Name)
		if err != nil {
			return fmt.Errorf("创建section失败:%s", err)
		}
	}
	err := i(g)
	if err != nil {
		return err
	}
	return nil
}
func i(g model.V1Group) error {
	cfg := global.Ini
	for _, host := range g.Host {
		val := "ansible_host=" + host.AnsibleHost + " " +
			"ansible_port=" + strconv.Itoa(host.AnsiblePort) + " " +
			"ansible_ssh_user=" + host.AnsibleSshUser + " " +
			"ansible_ssh_pass=" + host.AnsibleSshPass
		k := host.Alias
		_, err := cfg.Section(g.Name).NewKey(k, val)
		if err != nil {
			return fmt.Errorf("创建key失败:%s", err)
		}
		// 保存配置到文件
		err = cfg.SaveTo(global.Config.System.HostFile)
		if err != nil {
			return fmt.Errorf("保存文件失败:%s", err)
		}
	}
	return nil
}
func AddHandler(c *gin.Context) {
	var g model.V1Group
	err := c.ShouldBindJSON(&g)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	err = Add(g)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "添加成功"})
}
